package com.sugree.geopin;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.location.Location;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import com.sugree.geopin.PreferencesActivity;

public class GeoActivity extends MapActivity {
	private static final String TAG = "GeoPin";

	private static final int DIALOG_GOTO_ID = 0;

	protected Context mContext;
	protected TextView mInfoText;
	protected MapView mMapView;
	protected MapController mMapController;
	protected MyLocationOverlay mMyLocationOverlay;
	protected CenterOverlay mCenterOverlay;
	protected SharedPreferences mSP;
	protected Handler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
		mContext = getBaseContext();
        setContentView(R.layout.main);

		mSP = PreferenceManager.getDefaultSharedPreferences(this);

		mInfoText = (TextView)findViewById(R.id.info);
		mMapView = (MapView)findViewById(R.id.mapview);
		mMapView.setBuiltInZoomControls(true);

		mMapController = mMapView.getController();

		mMapController.setZoom(15);
		List<Overlay> overlays = mMapView.getOverlays();
		mMyLocationOverlay = new MyLocationOverlay(mContext, mMapView);
		overlays.add(mMyLocationOverlay);

		/*
		mMyLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mMapController.setCenter(mMyLocationOverlay.getMyLocation());
			}
		});
		*/

		Drawable drawable = getResources().getDrawable(R.drawable.pin);
		mCenterOverlay = new CenterOverlay(drawable);
		mMapView.getOverlays().add(mCenterOverlay);
		updateInfo();
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onStart() {
        super.onStart();
		mMyLocationOverlay.enableMyLocation();
	}

	@Override
	protected void onPause() {
        super.onPause();
		mMyLocationOverlay.disableMyLocation();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);

		Intent intent = new Intent(null, getIntent().getData());
		intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
		menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, GeoActivity.class), null, intent, 0, null);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_mylocation:
			mMapController.setCenter(mMyLocationOverlay.getMyLocation());
			break;

		case R.id.menu_goto:
			showDialog(DIALOG_GOTO_ID);
			break;

		case R.id.menu_copy:
			ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(mInfoText.getText());
			break;

		case R.id.menu_share:
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_TEXT, mInfoText.getText());
			startActivity(Intent.createChooser(intent, getText(R.string.share)));
			break;

		case R.id.menu_preferences:
			startActivity(new Intent(this, PreferencesActivity.class));
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch(id) {
		case DIALOG_GOTO_ID:
			LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.dialog_goto, null);
			final EditText lat = (EditText)layout.findViewById(R.id.latitude);
			final EditText lon = (EditText)layout.findViewById(R.id.longitude);
			dialog = new AlertDialog.Builder(this)
					.setView(layout)
					.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							GeoPoint p = new GeoPoint(
							(int)(Double.parseDouble(lat.getText().toString())*1e6),
							(int)(Double.parseDouble(lon.getText().toString())*1e6));
							mMapController.setCenter(p);
						}
					})
					.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.cancel();
						}
					})
					.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	protected void updateInfo() {
		GeoPoint p = mMapView.getMapCenter();
		String format = mSP.getString("display_format", "degrees");
		int type = Location.FORMAT_DEGREES;
		String text = null;
		if (format.equals("degrees")) {
			type = Location.FORMAT_DEGREES;
			text = p.getLatitudeE6()/1e6+","+p.getLongitudeE6()/1e6;
		} else if (format.equals("minutes")) {
			type = Location.FORMAT_MINUTES;
		} else if (format.equals("seconds")) {
			type = Location.FORMAT_SECONDS;
		}
		if (text == null) {
			text = Location.convert(p.getLatitudeE6()/1e6, type)+","+Location.convert(p.getLongitudeE6()/1e6, type);
		}
		mInfoText.setText(text);
	}

	public class CenterOverlay extends ItemizedOverlay<OverlayItem> {
		protected List<OverlayItem> mItems = new ArrayList<OverlayItem>();
		protected Drawable mMarker;

		public CenterOverlay(Drawable marker) {
			super(marker);
			mMarker = marker;
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mItems.get(i);
		}

		@Override
		public int size() {
			return mItems.size();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
			boundCenterBottom(mMarker);
			Overlay.drawAt(canvas, mMarker, (int)mapView.getWidth()/2, (int)mapView.getHeight()/2, shadow);
			updateInfo();
		}

		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				break;

			case MotionEvent.ACTION_MOVE:
			case MotionEvent.ACTION_UP:
				populate();
				break;
			}
			return super.onTouchEvent(event, mapView);
		}
	}
}
